package com.ruoyi.result.papers.controller;

import com.alibaba.excel.EasyExcel;
import com.ruoyi.common.annotation.DataScope;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.result.Result;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.result.papers.domain.ResultPapers;
import com.ruoyi.result.papers.domain.dto.ResultPapersDTO;
import com.ruoyi.result.papers.domain.vo.ResultPapersVO;
import com.ruoyi.result.papers.service.IResultPapersService;
import com.ruoyi.system.domain.result_entity.Export.CustomCellWriteHandler;
import com.ruoyi.system.domain.result_entity.Export.ExportField;
import com.ruoyi.system.domain.result_entity.Export.ExportRequest;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 论文Controller
 *
 * @author ruoyi
 * @date 2025-01-13
 */
@Slf4j
@RestController
@RequestMapping("/result/papers")
public class ResultPapersController extends BaseController
{
    @Autowired
    private IResultPapersService resultPapersService;

    /**
     * 查询论文列表
     */
    @DataScope(deptAlias = "d")
    @PreAuthorize("@ss.hasPermi('result:papers:list')")
    @GetMapping("/list")
    public TableDataInfo list(ResultPapersDTO resultPapers)
    {
        TableDataInfo list = resultPapersService.selectResultPapersList(resultPapers);
        return list;
    }

    /**
     * 导出论文列表
     */
    @PreAuthorize("@ss.hasPermi('result:papers:export')")
    @Log(title = "论文", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, ResultPapers resultPapers)
    {
//        List<ResultPapers> list = resultPapersService.selectResultPapersList(resultPapers);
//        ExcelUtil<ResultPapers> util = new ExcelUtil<ResultPapers>(ResultPapers.class);
//        util.exportExcel(response, list, "论文数据");
    }

    /**
     * excel批量导出
     */
    @PostMapping("/export/papers")
    @ApiOperation("excel批量导出")
    public void exportPapers(@RequestBody ExportRequest request, HttpServletResponse response) throws IOException {
        List<ExportField> fields = request.getFields();
        List<Map<String, Object>> data = request.getData();

        if (data.isEmpty()) {
            log.warn("Data is empty, no records to export.");
            return;
        }

        String fileName = "exported_papers.xlsx";
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        response.setHeader("Content-Disposition", "attachment; filename=" + fileName);

        // 动态生成表头
        List<List<String>> head = fields.stream()
                .map(field -> Arrays.asList(field.getLabel()))
                .collect(Collectors.toList());

        // 将 Map<String, Object> 转换为 List<List<Object>>
        List<List<Object>> transformedData = data.stream()
                .map(map -> fields.stream()
                        .map(field -> map.get(field.getKey()))
                        .collect(Collectors.toList()))
                .collect(Collectors.toList());
        log.info("转换后的数据：{}", transformedData);

        // 写入数据
        EasyExcel.write(response.getOutputStream())
                .head(head)
                .registerWriteHandler(new CustomCellWriteHandler(fields))
                .sheet("Papers")
                .doWrite(transformedData);
    }


    /**
     * 获取论文详细信息
     */
    @PreAuthorize("@ss.hasPermi('result:papers:query')")
    @GetMapping(value = "/getPapersById/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id)
    {
        ResultPapers resultPapers = resultPapersService.selectResultPapersById(id);
        if (resultPapers == null){
            log.error("论文不存在");
            return AjaxResult.error("论文不存在");
        }
        return AjaxResult.success(resultPapers);
    }

    /**
     * 批量获取论文详细信息
     */
    @GetMapping("/getPapersByIds")
    public AjaxResult getPapersByIds(@RequestParam(value = "ids", required = false) String idsStr) {
        if (StringUtils.isEmpty(idsStr)) {
            log.error("ids 参数为空");
            return AjaxResult.error("ids 参数为空");
        }

        // 将逗号分隔的字符串转换为 Long 数组
        Long[] ids = Arrays.stream(idsStr.split(","))
                .filter(s -> !StringUtils.isEmpty(s))
                .map(Long::parseLong)
                .toArray(Long[]::new);

        List<ResultPapersVO> resultPapersList = resultPapersService.selectResultPapersByIds(ids);
        if (resultPapersList == null || resultPapersList.isEmpty()) {
            log.error("论文不存在");
            return AjaxResult.error("论文不存在");
        }
        return AjaxResult.success(resultPapersList);
    }


    /**
     * 新增论文
     */
    @PreAuthorize("@ss.hasPermi('result:papers:add')")
    @Log(title = "论文", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody ResultPapers resultPapers)
    {
        return toAjax(resultPapersService.insertResultPapers(resultPapers));
    }

    /**
     * 修改论文
     */
    @PreAuthorize("@ss.hasPermi('result:papers:edit')")
    @Log(title = "论文", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody ResultPapers resultPapers)
    {
        return toAjax(resultPapersService.updateResultPapers(resultPapers));
    }

    /**
     * 删除论文
     */
    @PreAuthorize("@ss.hasPermi('result:papers:remove')")
    @Log(title = "论文", businessType = BusinessType.DELETE)
	@DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids)
    {
        return toAjax(resultPapersService.deleteResultPapersByIds(ids));
    }


    /**
     * 根据论文id主键删除论文
     */
    @DeleteMapping("/deleteById/{id}")
    @ApiOperation("根据论文id主键删除论文")
    public Result deleteById(@PathVariable Integer id){
        return resultPapersService.removePapersById(id);
    }


}
